import moment from 'moment';
import { Modal, notification } from 'antd';
import isObject from 'lodash/isObject';
import request from '@/utils/request';

const baseUrl = 'portal/LoginController';

const mapping = {
  CONFIRMING: 'CONFIRMING',
  LOG_OUT: 'LOG_OUT',
  LOGINED: 'LOGINED',
  SESSION_TIME_OUT: 'SESSION_TIME_OUT',
  LOCKED: 'LOCKED',
  POLLING_INTERVAL: 60, // 登录状态轮询间隔
  SUCC_CODE: '0000',
  LOGIN_ERROR_DIFF_IP_REGION: 'LOGIN_ERROR_DIFF_IP_REGION', // 登录IP不相同
  LOGIN_ERROR_PWD_STATUS_INACTIVE: 'LOGIN_ERROR_PWD_STATUS_INACTIVE', // 密码还没有激活
  LOGIN_ERROR_NON_WORK_HOUR: 'LOGIN_ERROR_NON_WORK_HOUR', // 非工作时间登录
  LOGIN_ERROR_DEFAULT_PWD: '62671', // 初始密码需要修改后才能登录
  LOGIN_NEED_DOUBLE_CHECK_SMS_CODE: '62677', // 需要二次短信验证码
  LOGIN_ERROR_SMS_CODE_EXPIRE: 'LOGIN_ERROR_SMS_CODE_EXPIRE', // 验证码失效
  LOGIN_ERROR_INVALIDATE_SMS_CODE: 'LOGIN_ERROR_INVALIDATE_SMS_CODE', // 验证码不正确
};

export default mapping;

let checking = false;

export async function login(params) {
  return request('portal/LoginController/login.do', {
    method: 'POST',
    data: params,
  });
}

export async function logout() {
  return request('portal/LoginController/logout.do', {
    method: 'GET',
  });
}

/**
 * 修改密码
 * @param {object} params
 * {
  userId: this.userId,
  userCode: this.options.userCode,
  password: pwds.pwd,
  newPwd: pwds.cfmPwd,
  pwdEffectDays: this.options.pwdEffectDays
}
 */
export async function updateUserPwd(params) {
  return request('orgauth/SystemUserController/updateSysUserPwd.do', { data: params });
}

/**
 * 检查是否会话超时
 * 预期回参：{"sessionTimeout":false,"lockFlag":false,"popoverMessages":[{msgContent,msgTitle,createDate,id}],"remindMessageCount":1}
 * 回参文档：http://portal.iwhalecloud.io/uportal.iwhalecloud.io/Rest-service.html#status0a3ca20id3dstatus3e203ca3e
 * @param {date} lastOpeDate 用户最后一次操作的时间 如: "2019-12-13 16:54:11"
 */
export async function status(lastOpeDate) {
  // 计算上一次操作的时间间隔分钟数
  const intervalMinute = Math.floor((+new Date() - +moment(lastOpeDate)) / 1000 / 60); // 单位分钟
  return request(`${baseUrl}/status.do`, {
    method: 'GET',
    data: { notip: 'yes', lastOpeDate, intervalMinute },
  });
}

export async function checkStatus(dispatch, lastOpDate) {
  if (checking || lastOpDate === null) {
    // 上次状态检查还没有成功
    return;
  }
  checking = true;

  // 预期回参：{"sessionTimeout":false,"lockFlag":false,"popoverMessages":[{msgContent,msgTitle,createDate,id}],"remindMessageCount":1}
  status(lastOpDate)
    .then(function(resp) {
      // 登录超时或被管理员强制下线
      if (isObject(resp) && resp.sessionTimeout) {
        // LoginInfo.timeoutFlag = true;
        if (!resp.invalidateMsg) {
          resp.invalidateMsg = '登录会话超时';
        }
        Modal.warning({
          title: '提醒',
          content: `${resp.invalidateMsg}，请重新登录`,
        });
        dispatch({
          type: 'login/logout',
        });
        return;
      }

      // 操作超时，锁定屏幕
      if (resp.lockFlag) {
        dispatch({
          type: 'login/lock',
        });
        return;
      }

      // 右下角消息提醒
      if (resp.popoverMessages && resp.popoverMessages.length > 0) {
        const first = resp.popoverMessages[0];
        notification.open({
          message: first.msgTitle,
          description: first.msgContent,
          placement: 'bottomRight',
          // icon: <Icon type="message" style={{ color: '#108ee9' }} />,
        });
      }

      // 右上角消息提醒数
      if (resp.remindMessageCount && resp.remindMessageCount > 0) {
        dispatch({
          type: 'notice/setNumber',
          payload: resp.remindMessageCount,
        });
      }
    })
    .finally(() => {
      checking = false;
    });
}

/**
 * 解锁屏幕
 * @param {object} password 密码
 */
export async function unlock(password) {
  return request(`${baseUrl}/unlock.do`, { data: { password } });
}

/**
 * 修改角色
 * @param {object} roleId
 * 预期回参 {userInfo:{roleId}}
 */
export async function changeRole(roleId) {
  return request(`${baseUrl}/changeRole.do`, {
    method: 'get',
    data: roleId,
  });
}

export async function getVcodeFlag() {
  return request(`${baseUrl}/getVcodeFlag.do`, { method: 'get' });
}

/**
 * 获取服务端ip
 * @param success
 */
export async function getClientIp(success) {
  return request(`${baseUrl}/getClientIp.do`, { method: 'get', success });
}

/**
 * 校验是否处于登录状态
 */
export async function logged() {
  return request(`${baseUrl}/logged.do`, { method: 'get' });
}

/**
 * 单点登录
 * @param params {object} 格式：{bssSessionId:123}
 */
export async function ssoLogin(params) {
  return request('pmc/pms/PmSsoLoginController/ssoLogin', {
    data: params,
  });
}
